﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SerialBrowserBridge.Devices;

namespace SerialBrowserBridge.WebServer.Handler
{
    public class FormHandler: IWebHandler
    {
        private IBlockDevice device; 

        public void Initialize(WebServerCore webServer)
        {
            device = webServer.Device;
        }

        public Object Process(Request request, Response response)
        {
            if (!request.URL.StartsWith("/.form"))
                return new HandleAction { Handled = false };

            var type = request.HasParameter(".type") ? request.Parameters[".type"] : "crlf_values";
            var endmarker = request.HasParameter(".endmarker") ? request.Parameters[".endmarker"] : "none";

            var formdata = new StringBuilder();
            var parameters = from pair in request.Parameters where !pair.Key.StartsWith(".") select pair;
            switch (type)
            {
                case "null_array_values":
                    parameters.ToList().ForEach(e => formdata.AppendFormat("{0}\0", e.Value));
                    formdata.Append('\0');
                    break;
                case "null_array_keyvalues":
                    parameters.ToList().ForEach(e => formdata.AppendFormat("{0}\0{1}\0", e.Key, e.Value));
                    formdata.Append('\0');
                    break;
                case "cr_values":
                    parameters.ToList().ForEach(e => formdata.AppendFormat("{0}\r", e.Value));
                    formdata.Append('\n');
                    break;
                case "cr_keyvalues":
                    parameters.ToList().ForEach(e => formdata.AppendFormat("{0}\r{1}\r", e.Key, e.Value));
                    formdata.Append('\n');
                    break;
                case "crlf_keyvalues":
                    parameters.ToList().ForEach(e => formdata.AppendFormat("{0}\r\n{1}\r\n", e.Key, e.Value));
                    formdata.Append("\r\n");
                    break;
                default:
                    parameters.ToList().ForEach(e => formdata.AppendFormat("{0}\r\n", e.Value));
                    break;
            }

            switch (endmarker)
            {
                case "null":
                    formdata.Append('\0');
                    break;
                case "cr":
                    formdata.Append('\r');
                    break;
                case "crlf":
                    formdata.Append("\r\n");
                    break;
                default:
                    break;
            }

            device.WriteBlock(formdata.ToString());

            return new RedirectAction { URL = "/" };
        }

        public int Priority
        {
            get { return 100; }
        }
    }
}
